package org.lin.shortlink.controller;

import org.lin.shortlink.core.ApiResponse;
import org.lin.shortlink.core.ResponseEnums;
import org.lin.shortlink.core.pojo.Link;
import org.lin.shortlink.service.LinkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@RestController
public class LinkController {
    @Autowired
    private LinkService linkService;

    /**
     * 长链接转短链接
     * @param link 参数
     * @return
     */
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public ApiResponse createShotUrl(@RequestBody Link link) {
        if (link.getLongUrl().startsWith("http://") || link.getLongUrl().startsWith("https://")) {
            String shortUrl = linkService.save(link.getLongUrl());
            return ApiResponse.response(ResponseEnums.SUCCESS, shortUrl);
        } else {
            return ApiResponse.response(ResponseEnums.LONG_URL_FAIL);
        }
    }

    /**
     * 短链接302到长链接
     * @param url 短链接
     * @param response 响应
     * @throws IOException
     */
    @RequestMapping("/{url}")
    public void redirectUrl(@PathVariable("url") String url, HttpServletResponse response) throws IOException {
        Link byShortUrl = linkService.findByShortUrl(url);
        if (Objects.isNull(byShortUrl)) {
            return ;
        }
        response.sendRedirect(byShortUrl.getLongUrl());
    }
}
